from datetime import datetime
import time
from typing import List

import pydantic
from fastapi_pagination.ext.databases import paginate
from sqlalchemy import insert, select, update

from forward.api.admin.schemas.system import (
    SystemAuthPostAddInSchema,
    SystemAuthPostEditInSchema,
    SystemAuthPostOutSchema,
)
from forward.dependencies.database import db
from forward.model.tables.system import SystemAuthPostModel, SystemAuthAdminModel


class SystemAuthPostService:

    async def fetch_all(self):
        post_all = await db.fetch_all(
            select(SystemAuthPostModel)
            .where(SystemAuthPostModel.is_delete == 0)
            .order_by(SystemAuthPostModel.sort)
        )
        return [
            SystemAuthPostOutSchema.model_validate(post, from_attributes=True)
            for post in post_all
        ]

    async def fetch_list(
        self, code: str = "", name: str = "", is_stop: int | None = None
    ):
        where = [SystemAuthPostModel.is_delete == 0]
        if code:
            where.append(SystemAuthPostModel.code == code)
        if name:
            where.append(SystemAuthPostModel.name.like("%{0}%".format(name)))
        if is_stop:
            where.append(SystemAuthPostModel.is_stop == is_stop)
        query = (
            select(SystemAuthPostModel)
            .select_from(SystemAuthPostModel)
            .where(*where)
            .order_by(SystemAuthPostModel.sort)
        )
        return await paginate(db, query)

    async def add(self, post_add_in: SystemAuthPostAddInSchema):
        assert not await db.fetch_one(
            select(SystemAuthPostModel)
            .where(
                SystemAuthPostModel.code == post_add_in.code
                or SystemAuthPostModel.name == post_add_in.name,
                SystemAuthPostModel.is_delete == 0,
            )
            .limit(1)
        ), "该岗位已存在"
        create_post = post_add_in.model_dump()

        query = insert(SystemAuthPostModel).values(**create_post)
        return await db.execute(query)

    async def edit(self, post_edit_in: SystemAuthPostEditInSchema):
        assert await db.fetch_one(
            select(SystemAuthPostModel).where(
                SystemAuthPostModel.id == post_edit_in.id,
                SystemAuthPostModel.is_delete == 0,
            )
        ), "岗位不存在"

        assert not await db.fetch_one(
            select(SystemAuthPostModel)
            .where(
                SystemAuthPostModel.id != post_edit_in.id,
                SystemAuthPostModel.code == post_edit_in.code
                or SystemAuthPostModel.name == post_edit_in.name,
                SystemAuthPostModel.is_delete == 0,
            )
            .limit(1)
        ), "该岗位已存在"

        edit_post = post_edit_in.model_dump()

        return await db.execute(
            update(SystemAuthPostModel)
            .where(SystemAuthPostModel.id == post_edit_in.id)
            .values(**edit_post)
        )

    async def delete(self, _id):
        assert await db.fetch_one(
            select(SystemAuthPostModel).where(
                SystemAuthPostModel.id == _id, SystemAuthPostModel.is_delete == 0
            )
        ), "岗位不存在"

        assert not await db.fetch_one(
            select(SystemAuthAdminModel)
            .where(
                SystemAuthAdminModel.post_ids == _id,
                SystemAuthAdminModel.is_delete == 0,
            )
            .limit(1)
        ), "该岗位已被管理员使用,请先移除"

        return await db.execute(
            update(SystemAuthPostModel)
            .where(SystemAuthPostModel.id == _id)
            .values(is_delete=1, deleted_time=datetime.now())
        )

    async def detail(self, _id):
        post_detail = await db.fetch_one(
            select(SystemAuthPostModel)
            .where(SystemAuthPostModel.id == _id, SystemAuthPostModel.is_delete == 0)
            .limit(1)
        )
        assert post_detail, "岗位不存在"
        return post_detail

    @classmethod
    async def instance(cls):
        return cls()
